package com.lingkang.ngfile.config.security;

import com.lingkang.ngfile.service.impl.CustomUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired  // 登录成功，自定义返回结果
    private AjaxAuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired  //  登录失败返，自定义返回结果
    private AjaxAuthenticationFailureHandler authenticationFailureHandler;

    //注入我们加密的方式，spring5+以上必须要加密密码，这是官网推荐的加密方式，也可选择MD5
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //由于我们自定义了UserDetailsService，我们需要新注入这个bean
    @Bean
    @Override //重写
    public UserDetailsService userDetailsServiceBean() {
        //使用我们自定义的 UserDetailsService
        return new CustomUserDetailsServiceImpl();
    }

    //认证----自定义认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //自定义认证
        auth.userDetailsService(userDetailsServiceBean());
    }

    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //授权规则，除了要授权的，其他所有人能访问
        http.authorizeRequests()
                .antMatchers("/user/**").hasAnyRole("USER")
                .anyRequest().permitAll(); //其他页面所有人能访问

        //启动登陆页面
        //定制登陆页面，表单提交的路径loginProcessingUrl
        http.formLogin().loginPage("/login")
                .loginProcessingUrl("/login");

        //注销功能 ,跳回首页
        //关闭跨域认证请求，否则你需要post来注销
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/")
                .and().csrf().disable();

        //自定义登陆返回的结果，用于ajax异步
        http.formLogin().successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler).permitAll();

        //允许在frame上显示
        http.headers().frameOptions().disable();

        //开启记住我功能，表单提交remember的参数
//        http.rememberMe().rememberMeParameter("remember");
    }
}
